package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * ${table.comment!} 服务实现类
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

    @Override
    public ${entity} getByIdWithDetails(Long id) {
        if (id == null) {
            log.warn("查询${table.comment!}详情时，ID不能为空");
            return null;
        }
        try {
            return baseMapper.selectByIdWithDetails(id);
        } catch (Exception e) {
            log.error("查询${table.comment!}详情失败，ID: {}", id, e);
            throw new RuntimeException("查询${table.comment!}详情失败", e);
        }
    }

    @Override
    public IPage<${entity}> pageList(Page<${entity}> page, ${entity} entity) {
        try {
            return baseMapper.selectPageList(page, entity);
        } catch (Exception e) {
            log.error("分页查询${table.comment!}列表失败", e);
            throw new RuntimeException("分页查询${table.comment!}列表失败", e);
        }
    }

    @Override
    public List<${entity}> listByCondition(${entity} entity) {
        try {
            return baseMapper.selectList(entity);
        } catch (Exception e) {
            log.error("查询${table.comment!}列表失败", e);
            throw new RuntimeException("查询${table.comment!}列表失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(${entity} entity) {
        if (entity == null) {
            log.warn("新增${table.comment!}时，实体不能为空");
            return false;
        }
        try {
            // 可以在这里添加业务逻辑验证
            validateEntity(entity);
            
            int result = baseMapper.insert(entity);
            if (result > 0) {
                log.info("新增${table.comment!}成功，ID: {}", entity.<#list table.fields as field><#if field.keyFlag>${field.propertyName}</#if></#list>);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("新增${table.comment!}失败", e);
            throw new RuntimeException("新增${table.comment!}失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(${entity} entity) {
        if (entity == null || entity.<#list table.fields as field><#if field.keyFlag>get${field.capitalName}()</#if></#list> == null) {
            log.warn("更新${table.comment!}时，实体或ID不能为空");
            return false;
        }
        try {
            // 检查记录是否存在
            ${entity} existingEntity = baseMapper.selectById(entity.<#list table.fields as field><#if field.keyFlag>get${field.capitalName}()</#if></#list>);
            if (existingEntity == null) {
                log.warn("更新${table.comment!}时，记录不存在，ID: {}", entity.<#list table.fields as field><#if field.keyFlag>get${field.capitalName}()</#if></#list>);
                return false;
            }
            
            // 可以在这里添加业务逻辑验证
            validateEntity(entity);
            
            int result = baseMapper.updateById(entity);
            if (result > 0) {
                log.info("更新${table.comment!}成功，ID: {}", entity.<#list table.fields as field><#if field.keyFlag>get${field.capitalName}()</#if></#list>);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新${table.comment!}失败", e);
            throw new RuntimeException("更新${table.comment!}失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        if (id == null) {
            log.warn("删除${table.comment!}时，ID不能为空");
            return false;
        }
        try {
            // 检查记录是否存在
            ${entity} existingEntity = baseMapper.selectById(id);
            if (existingEntity == null) {
                log.warn("删除${table.comment!}时，记录不存在，ID: {}", id);
                return false;
            }
            
            int result = baseMapper.deleteById(id);
            if (result > 0) {
                log.info("删除${table.comment!}成功，ID: {}", id);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除${table.comment!}失败，ID: {}", id, e);
            throw new RuntimeException("删除${table.comment!}失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            log.warn("批量删除${table.comment!}时，ID列表不能为空");
            return false;
        }
        try {
            int result = baseMapper.deleteBatchIds(ids);
            if (result > 0) {
                log.info("批量删除${table.comment!}成功，数量: {}", result);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("批量删除${table.comment!}失败", e);
            throw new RuntimeException("批量删除${table.comment!}失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createBatch(List<${entity}> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            log.warn("批量新增${table.comment!}时，实体列表不能为空");
            return false;
        }
        try {
            // 验证每个实体
            for (${entity} entity : entityList) {
                validateEntity(entity);
            }
            
            int result = baseMapper.insertBatch(entityList);
            if (result > 0) {
                log.info("批量新增${table.comment!}成功，数量: {}", result);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("批量新增${table.comment!}失败", e);
            throw new RuntimeException("批量新增${table.comment!}失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatch(List<${entity}> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            log.warn("批量更新${table.comment!}时，实体列表不能为空");
            return false;
        }
        try {
            // 验证每个实体
            for (${entity} entity : entityList) {
                if (entity.<#list table.fields as field><#if field.keyFlag>get${field.capitalName}()</#if></#list> == null) {
                    throw new IllegalArgumentException("批量更新时，每个实体的ID不能为空");
                }
                validateEntity(entity);
            }
            
            int result = baseMapper.updateBatch(entityList);
            if (result > 0) {
                log.info("批量更新${table.comment!}成功，数量: {}", result);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("批量更新${table.comment!}失败", e);
            throw new RuntimeException("批量更新${table.comment!}失败", e);
        }
    }

    @Override
    public long countByCondition(${entity} entity) {
        try {
            return baseMapper.countByCondition(entity);
        } catch (Exception e) {
            log.error("统计${table.comment!}数量失败", e);
            throw new RuntimeException("统计${table.comment!}数量失败", e);
        }
    }

    @Override
    public boolean exists(${entity} entity) {
        try {
            long count = baseMapper.countByCondition(entity);
            return count > 0;
        } catch (Exception e) {
            log.error("检查${table.comment!}是否存在失败", e);
            throw new RuntimeException("检查${table.comment!}是否存在失败", e);
        }
    }

    /**
     * 验证实体数据
     *
     * @param entity 实体对象
     */
    private void validateEntity(${entity} entity) {
        if (entity == null) {
            throw new IllegalArgumentException("${table.comment!}实体不能为空");
        }
        
        // 可以在这里添加具体的业务验证逻辑
        // 例如：必填字段验证、数据格式验证、业务规则验证等
        
<#list table.fields as field>
<#if field.comment?? && field.comment?contains("必填")>
        if (entity.get${field.capitalName}() == null<#if field.propertyType == "String"> || entity.get${field.capitalName}().trim().isEmpty()</#if>) {
            throw new IllegalArgumentException("${field.comment}不能为空");
        }
</#if>
</#list>
    }
}
</#if>